﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;

namespace TireService.Web.View.ResourceView
{
    public partial class GeographicalAreaList : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

            }

            // Bind data to gridview
            BindGeographicalArea(db);
            try
            {
                int servicegeoareaid = Convert.ToInt32(gvGeographicalArea.GetRowValues(gvGeographicalArea.FocusedRowIndex, "ServiceGeoAreaId"));
                int countryid = Convert.ToInt32(gvGeographicalArea.GetRowValues(gvGeographicalArea.FocusedRowIndex, "CountryId"));
                BindGeographicalAreaZipCodeList(db, servicegeoareaid, countryid);
            }
            catch (Exception)
            {
                // Nothing - no area selected
            }


            // Change gridview pagesize based on dropdownlist
            gvGeographicalArea.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind area data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindGeographicalArea(TireServiceDB db)
        {
            gvGeographicalArea.DataSource = db.GetServiceGeographicalAreas();
            gvGeographicalArea.DataBind();

            // Prepare data for editmode of area
            GridViewDataComboBoxColumn ddlCountry = gvGeographicalArea.Columns["CountryDropdown"] as GridViewDataComboBoxColumn;
            ddlCountry.PropertiesComboBox.ValueType = typeof(int);
            ddlCountry.PropertiesComboBox.DataSource = db.GetCountries();
            ddlCountry.PropertiesComboBox.TextField = "CountryName";
            ddlCountry.PropertiesComboBox.ValueField = "CountryId";
            ddlCountry.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlCountry.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
        }

        /// <summary>
        /// Function that bind zipcode list for selected area to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceGeoAreaId">Id on service geographical area</param>
        /// <param name="CountryId">Id on country</param>
        private void BindGeographicalAreaZipCodeList(TireServiceDB db, int ServiceGeoAreaId, int CountryId)
        {
            // Bind to gridview
            gvGeographicalAreaZipCodeList.DataSource = db.GetServiceGeographicalAreaZipCodeLists(ServiceGeoAreaId).OrderBy(p => p.ZipCode);
            gvGeographicalAreaZipCodeList.DataBind();

            // Prepare data for editmode of area
            GridViewDataComboBoxColumn ddlZipCodeList = gvGeographicalAreaZipCodeList.Columns["ZipCodeDropdown"] as GridViewDataComboBoxColumn;
            ddlZipCodeList.PropertiesComboBox.ValueType = typeof(int);
            ddlZipCodeList.PropertiesComboBox.DataSource = db.GetCountryZipCodeLists(CountryId).OrderBy(p => p.ZipCode);
            //ddlZipCodeList.PropertiesComboBox.TextField = "CountryName";
            ddlZipCodeList.PropertiesComboBox.Columns.Clear();
            ddlZipCodeList.PropertiesComboBox.Columns.Add("ZipCode", "Postnr");
            ddlZipCodeList.PropertiesComboBox.Columns.Add("City", "By");
            ddlZipCodeList.PropertiesComboBox.ValueField = "ZipCode";
            ddlZipCodeList.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlZipCodeList.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
        }

        #region Private Functions

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvGeographicalArea.ClearSort();
            gvGeographicalArea.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:
                    // Nothing - clear grouping

                    break;
                case 1:
                    gvGeographicalArea.GroupBy(gvGeographicalArea.Columns["City"]);

                    break;
                //case 2:
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //    break;
                //case 3:
                //    gvOrder.GroupBy(gvOrder.Columns["PhotoDate"]);
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //break;
            }
            gvGeographicalArea.ExpandAll();
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #endregion


        #region GridView Functions

        /// <summary>
        /// Gridview function for creating area
        /// </summary>
        protected void gvGeographicalArea_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            ServiceGeographicalArea area = new ServiceGeographicalArea();

            area.CountryId = Convert.ToInt32(e.NewValues["CountryId"]);
            area.Description = Convert.ToString(e.NewValues["Description"]);

            db.AddServiceGeographicalArea(area);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvGeographicalArea.CancelEdit();

            // Refresh gridview
            BindGeographicalArea(db);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for updating area
        /// </summary>
        protected void gvGeographicalArea_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            // Get id
            int servicegeoareaid = Convert.ToInt32(e.Keys["ServiceGeoAreaId"]);

            TireServiceDB db = new TireServiceDB();

            ServiceGeographicalArea area = new ServiceGeographicalArea();

            // Fecth existing area
            area = db.GetServiceGeographicalArea(servicegeoareaid);

            if (area != null)
            {
                area.CountryId = Convert.ToInt32(e.NewValues["CountryId"]);
                area.Description = Convert.ToString(e.NewValues["Description"]);
            }
            else
            {
                // Customer subscription does not exists
                throw new ArgumentException("Område eksistere ikke");
            }

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvGeographicalArea.CancelEdit();

            // Refresh gridview
            BindGeographicalArea(db);

            // Close db connection
            db.Dispose();
        }

        protected void gvGeographicalAreaZipCodeList_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            try
            {
                int servicegeoareaid = Convert.ToInt32(gvGeographicalArea.GetRowValues(gvGeographicalArea.FocusedRowIndex, "ServiceGeoAreaId"));
                int countryid = Convert.ToInt32(gvGeographicalArea.GetRowValues(gvGeographicalArea.FocusedRowIndex, "CountryId"));
                BindGeographicalAreaZipCodeList(db, servicegeoareaid, countryid);
            }
            catch (Exception)
            {
                // Nothing - no area selected
            }

        }

        /// <summary>
        /// Gridview function for creating zipcode in area
        /// </summary>
        protected void gvGeographicalAreaZipCodeList_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            ServiceGeographicalAreaZipCodeList areazipcode = new ServiceGeographicalAreaZipCodeList();

            int servicegeoareaid = Convert.ToInt32(gvGeographicalArea.GetRowValues(gvGeographicalArea.FocusedRowIndex, "ServiceGeoAreaId"));
            int countryid = Convert.ToInt32(gvGeographicalArea.GetRowValues(gvGeographicalArea.FocusedRowIndex, "CountryId"));

            areazipcode.ServiceGeoAreaId = servicegeoareaid;
            areazipcode.CountryId = countryid;
            areazipcode.ZipCode = Convert.ToString(e.NewValues["ZipCode"]);

            db.AddServiceGeographicalAreaZipCodeList(areazipcode);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvGeographicalAreaZipCodeList.CancelEdit();

            // Refresh gridview
            BindGeographicalAreaZipCodeList(db, areazipcode.ServiceGeoAreaId, areazipcode.CountryId);

            // Close db connection
            db.Dispose();
        }

        /// <summary>
        /// Gridview function for deleting zipcode in area
        /// </summary>
        protected void gvGeographicalAreaZipCodeList_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            int AreaZipCodeId = Convert.ToInt32(e.Keys);

            ServiceGeographicalAreaZipCodeList areazipcode = db.GetServiceGeographicalAreaZipCodeList(AreaZipCodeId);

            int ServiceGeoAreaId = areazipcode.ServiceGeoAreaId;
            int CountryId = areazipcode.CountryId;

            db.RemoveServiceGeographicalAreaZipCodeList(areazipcode);

            // Commit changes to database
            db.SubmitChanges();

            // End edit mode
            e.Cancel = true;
            gvGeographicalAreaZipCodeList.CancelEdit();

            // Refresh gridview
            BindGeographicalAreaZipCodeList(db, ServiceGeoAreaId, CountryId);

            // Close db connection
            db.Dispose();
        }

        #endregion

    }
}